package com.kaifamiao.deno;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 创建线程，两个线程对j+1  100次,两个线程对j-1 100次
 * 1.定义一个j addNum subNum
 * 2.创建内部类  实现Runnable 接口 重写run()
 * 3.加锁
 * 4.创建线程，启动线程
 *
 */
public class Test {
    private volatile int j;
    private int addNum;
    private int subNum;
    class AddRunnable implements Runnable{

        private Lock lock = new ReentrantLock();
        @Override
        public void run() {
            while (addNum < 100){
                try{
                    j++;
                    System.out.println(Thread.currentThread().getName() + "对j+1,当前j="+j);
                    addNum++;
                }finally {
                }

            }
        }
    }

    class SubRunnable implements Runnable{

        @Override
        public void run() {
            while (subNum < 100){
                try{
                    j--;
                    System.out.println(Thread.currentThread().getName() + "对j-1,当前j="+j);
                    subNum++;
                }finally {
                }

            }
        }
    }

    public static void main(String[] args) {
        Test t = new Test();
        AddRunnable addRunnable = t.new AddRunnable();
        SubRunnable subRunnable = t.new SubRunnable();

        new Thread(addRunnable,"增加线程1号").start();
        new Thread(subRunnable,"减小线程1号").start();
        new Thread(addRunnable,"增加线程2号").start();
        new Thread(subRunnable,"减小线程2号").start();
    }

}
